/*********************************************************************************
  *Copyright (C), 2016-2022, zhangjiance Tech. Co., Ltd.
  *FileName:  thread_task_common.h
  *Author:  JianCe.Zhang
  *Version:  V1.0
  *Date: 2023-06-08
  *Description: 
  *Function List:
  * 1. void function(void)
  * 2. 
  * 3. 
  * 4. 
  *History:
  * 1. 2022.8.28;JianCe.Zhang;Init Function 
  * 2. 
  * 3. 
  * 4. 
**********************************************************************************/

#ifndef  __thread_task_common_H__
#define  __thread_task_common_H__


/***************************************Includes***********************************/
#include <thread>
#include <future>
#include <iostream>

/***************************************Macros***********************************/


/***************************************Variables***********************************/



/***************************************Functions***********************************/

namespace zhangjiance
{
namespace upgradeservice
{
    

enum class Result:int
{
    Fail = -1,
    Running = 0,
    OK = 1,
};

class ThreadTask
{
protected:
    /* Future object which will hold the return value of the function when it's available. */
    std::future<void> future;
    std::atomic<bool> stop_flag;
    Result result;

public:
    /* Destructor: if task is running, wait for it to complete. */
    virtual ~ThreadTask() noexcept
    {
        if (future.valid())
            future.wait();
    }
    /* Checks if the task has been completed. */
    bool is_done()
    {
        return future.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
    }

    void set_stop_flag(bool flag)
    {
        stop_flag.store(flag);
    }

    bool get_stop_flag() const
    {
        return stop_flag.load();
    }

    /* Returns the result of the operation. */
    Result get_result() const
    {
        return result;
    }

private:
    /* Pure virtual function for running the task.  */
    /* Needs to be implemented by child classes. */
    virtual void run() = 0;
    ThreadTask& operator=(const ThreadTask&) = delete;
};

}  // namespace upgradeservice
}  // namespace zhangjiance

#endif
/* [] END OF thread_task_common.h */